package com.qianniu.napi.admin.service.akka;

import akka.actor.UntypedActor;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.IService;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.*;
import com.qianniu.napi.admin.entity.penum.ActgxType;
import com.qianniu.napi.admin.entity.penum.JftypeEnum;
import com.qianniu.napi.admin.entity.penum.Jptype;
import com.qianniu.napi.admin.service.*;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.ObjectUtil;
import com.qianniu.napi.common.util.SpringUtil;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;

import java.util.Date;

public class UserActor extends UntypedActor {

    private final static Logger logger = LoggerFactory.getLogger(UserActor.class);

    private IActgxService actgxService = (IActgxService) SpringUtil.getBean("actgxServiceImpl");
    private IUserService userService = (IUserService) SpringUtil.getBean("userServiceImpl");
    private IUserstatService userstatService = (IUserstatService) SpringUtil.getBean("userstatServiceImpl");
    private IFensService fensService = (IFensService) SpringUtil.getBean("fensServiceImpl");

//    private IUserstatService userstatService = (IUserstatService) SpringUtil.getBean("IUserstatService");
//    private String[] names = SpringUtil.getApplicationContext().getBeanDefinitionNames();
//    private String[] aliass = SpringUtil.getApplicationContext().getAliases("IUserService");

    @Override
    public void onReceive(Object message) {
        logger.info(">>>>>>UserActor in");

        if (message instanceof String) {
            String msg = message.toString();
            logger.info(">>>>>>UserActor receive message:" + msg);

            // 格式 type+uid+toke
            String[] arr = msg.split("@");
            logger.info(">>>>>>receive arr.length:" + arr.length);
//            if (arr.length < 3) return;

            String type = arr[0];
            String ywid = arr[1];
//            String wxType = arr[2];
            String exta = null;

            switch (type) {
                case Constants.AKKA_MSG_CUSERSTAT:
                    createUserstat(ywid);
                    break;
                case Constants.AKKA_MSG_ACCESS_USERSTAT:
//                    accessUserstat(ywid);
                    break;
                case Constants.AKKA_MSG_VISIT_USERSTAT:
                    visitUserstat(ywid);
                    break;
                case Constants.AKKA_MSG_FENXIAO_ORI:
                    exta = arr[2];
                    fenxiaoOri(ywid,exta);
                    break;
                case Constants.AKKA_MSG_FENXIAO_SCENE:
                    exta = arr[2];
                    fenxiaoScene(ywid,exta);
                    break;
                default:
                    return;
            }
        }
    }

    // 实时生成图片
    private void createUserstat(String uid) {
        logger.info(">>>>>> createUserstat in");

        Wrapper<User> entity = new EntityWrapper<User>().setSqlSelect("id,name,guid,mid,mpid").eq("id", uid);
        User user = userService.selectOne(entity);

        Userstat ustat = new Userstat();
        ustat.setUid(user.getId());
        ustat.setGuid(user.getGuid());
        ustat.setMid(user.getMid());
        ustat.setMpid(ObjectUtil.getMpid());

        ustat.setAccess(0);
        ustat.setVisit(0);

        ustat.setAccessc(0);
        ustat.setVisitc(0);

        ustat.setGfav(0);
        ustat.setUfav(0);
        ustat.setZuan(0);

        ustat.setKehu(0);
        ustat.setShare(0);
        ustat.setCall(0);
        ustat.setShuo(0);
        ustat.setDongtai(0);

        ustat.setKehu(0);
        ustat.setRenqi(1);
        ustat.setState(1);
        ustat.setIsHuoyue(1);
        ustat.setLastvtime(new Date());
        ustat.setCreatetime(new Date());

        logger.info(">>>>>>ustat.insert");
        ustat.insert();
    }

    // 朋友圈分享
    private void fenxiaoScene(String ywid,String exta) {
        logger.info(">>>>>> fenxiaoScene in ywid=" + ywid);
        logger.info(">>>>>> fenxiaoScene in exta=" + exta);
        String[] arr = ywid.split("_");
        logger.info(">>>>>>receive arr.length:" + arr.length);
        if(arr.length<3)return;

        String puid = arr[0];
//        User puser = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,nick_name nickName,avatar_pic avatarPic,is_member isMember," +
//                "member_level memberLevel,is_mch isMch,is_platform isPlatform,is_agent isAgent")
//                .eq("id",uid));

        // =====待完善【缺少奖励逻辑】
        User cuser = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,nick_name nickName,avatar_pic avatarPic,mid,mpid").eq("id",exta));

//        logger.debug("====puser="+ JSON.toJSONString(puser));
        logger.debug("====cuser="+ JSON.toJSONString(cuser));
//        if(puser==null||cuser==null)return;
        if(cuser==null)return;

        int count = fensService.selectCount(new EntityWrapper<Fens>().eq("uid",cuser.getId()).eq("puid",puid));
        if(count>0)return;

        Fens fens = new Fens();
        fens.setUid(cuser.getId());
        fens.setNickname(cuser.getNickName());
        fens.setAvatarpic(cuser.getAvatarPic());
        fens.setPuid(Long.valueOf(puid));

        fens.setLevelType(1);
        fens.setStatus(1);
        fens.setState(1);
        fens.setOriginType(1);//转发
        fens.setPage(arr[1]);//转发页
        fens.setAct(arr[2]);//转发页
        if(arr.length>3)fens.setYwid(arr[3]);
        fens.setMid(cuser.getMid());
        fens.setMpid(cuser.getMpid());
        fens.setCreatetime(new Date());
        fens.insert();
        logger.debug("======1th fensi insert OK");

        //处理二级粉丝

        Fens pfens = fensService.selectOne(new EntityWrapper<Fens>().setSqlSelect("id,puid").eq("uid",puid).orderBy("status",false));

        if(pfens!=null){
            count = fensService.selectCount(new EntityWrapper<Fens>().eq("uid",cuser.getId()).eq("puid",pfens.getPuid()));
            if(count>0)return;

            fens.setId(null);
            fens.setPuid(pfens.getPuid());
            fens.setLevelType(2);
            fens.insert();
            logger.debug("======2th fensi insert OK");
        }
    }

    // 页面转发
    private void fenxiaoOri(String ywid,String exta) {
        logger.info(">>>>>> fenxiaoOri in ywid=" + ywid);
        logger.info(">>>>>> fenxiaoOri in exta=" + exta);
        String[] arr = ywid.split("_");
        logger.info(">>>>>>receive arr.length:" + arr.length);
        if(arr.length<3)return;

        String guid = arr[0];
        User puser = userService.selectOne(new EntityWrapper<User>().setSqlSelect("id,nick_name nickName,avatar_pic avatarPic,is_member isMember," +
                "member_level memberLevel,is_mch isMch,is_platform isPlatform,is_agent isAgent")
                .eq("guid",guid));

        User cuser = userService.selectById(exta);
        logger.debug("====puser="+ JSON.toJSONString(puser));
        logger.debug("====cuser="+ JSON.toJSONString(cuser));
        if(puser==null||cuser==null)return;

        int count = fensService.selectCount(new EntityWrapper<Fens>().eq("uid",cuser.getId()).eq("puid",puser.getId()));
        if(count>0)return;

        Fens fens = new Fens();
        fens.setUid(cuser.getId());
        fens.setNickname(cuser.getNickName());
        fens.setAvatarpic(cuser.getAvatarPic());
        fens.setPuid(puser.getId());

        fens.setLevelType(1);
        fens.setStatus(1);
        fens.setState(1);
        fens.setOriginType(3);//转发
        fens.setPage(arr[1]);//转发页
        fens.setAct(arr[2]);//转发页
        if(arr.length>3)fens.setYwid(arr[3]);
        fens.setMid(cuser.getMid());
        fens.setMpid(cuser.getMpid());
        fens.setCreatetime(new Date());
        fens.insert();
        logger.debug("======1th fensi insert OK");

        //处理二级粉丝
        Fens pfens = fensService.selectOne(new EntityWrapper<Fens>().setSqlSelect("id,puid").eq("uid",puser.getId()).orderBy("status",false));
        if(pfens!=null){
            count = fensService.selectCount(new EntityWrapper<Fens>().eq("uid",cuser.getId()).eq("puid",pfens.getPuid()));
            if(count>0)return;

            fens.setId(null);
            fens.setPuid(pfens.getPuid());
            fens.setLevelType(2);
            fens.insert();
            logger.debug("======2th fensi insert OK");
        }
    }

    // 我访问的
    private void visitUserstat(String ywid) {
        logger.info(">>>>>> accessUserstat in ywid=" + ywid);
        String[] arr = ywid.split("##");
//            recordAct(Long uid, Long vuid, Long mid, Long mpid, int type +"_"+ip+"_"+os;);

        logger.info(">>>>>>receive arr.length:" + arr.length);
//            if (arr.length < 3) return;

        Long uid = 0l;
        Long vuid = 0l;
        Long mid = 0l;
        Long mpid = 0l;

        try {
            uid = Long.parseLong(arr[0]);
            vuid = Long.parseLong(arr[1]);
            mid = Long.parseLong(arr[2]);
            mpid = Long.parseLong(arr[3]);
        } catch (Exception e) {
        }

        int type = 1;
        try {
            type = Integer.parseInt(arr[4]);
        } catch (Exception e) {

        }
        String ip = arr[5];
        String os = arr[6];

        this.recordAct(uid, vuid, mid, mpid, type, ip, os);
    }

    // 记录当前用户的行为
    public void recordAct(Long uid, Long vuid, Long mid, Long mpid, int type, String ip, String os) {
        logger.debug("=========start to recordAct");

        Wrapper<Actgx> aentity = new EntityWrapper<Actgx>().setSqlSelect("id,uid,type,renqi").eq("type", type)
                .eq("uid", uid).eq("vuid", vuid).eq("isfirst", 1);
        int ucout = actgxService.selectCount(aentity);

        int vcout = 1;
        if (type == ActgxType.visit.getVal()) {
            Wrapper<Actgx> ventity = new EntityWrapper<Actgx>().setSqlSelect("id,uid,type,renqi").eq("type", type)
                    .eq("uid", vuid).eq("vuid", uid).eq("isfirst", 1);
            vcout = actgxService.selectCount(ventity);
        }
        Actgx act = new Actgx();
        act.setUid(uid);
        act.setVuid(vuid);

        act.setMid(mid);
        act.setQqcount(0);
        act.setMpid(ObjectUtil.getMpid());
        act.setCreatetime(new Date());

        Wrapper<Userstat> raentity = new EntityWrapper<Userstat>().setSqlSelect("id,uid,renqi").eq("uid", vuid);
        Userstat ractgx = userstatService.selectOne(raentity);
        int renqi = 1;
        if (ractgx != null && ractgx.getRenqi() != null) {
            renqi = ractgx.getRenqi() + 1;
        }

        act.setType(type);
        act.setIp(ip);
        act.setRenqi(renqi);
        act.setIsfirst(ucout == 0 ? 1 : 0);
        act.setTerminal(os);

        if (ractgx != null) {
            Actgx empty = new Actgx();
            empty.setUid(uid);
            empty.setRenqi(renqi);

            Wrapper<Actgx> update = new EntityWrapper<Actgx>().ge("type", 3).or()
                    .le("type", 5).ne("type", 4).eq("uid", uid);
            actgxService.update(empty, update);
        }


        Wrapper<User> entity = new EntityWrapper<User>().setSqlSelect("id,name,company,gs,phone,duty,hasmp,gongkai,avatar_pic avatarPic,nick_name nickName,hangye,weixin,photo,guid")
                .eq("state", 1).eq("id", vuid);

        User user = userService.selectOne(entity);
        act.setName(Strings.isNullOrEmpty(user.getName()) ? user.getNickName() : user.getName());
        act.setAvatar(Strings.isNullOrEmpty(user.getPhoto()) ? user.getAvatarPic() : user.getPhoto());
        act.setPhone(user.getPhone());
        act.setGuid(user.getGuid());

//        if (type >= 3 && type <= 5) { // 只保留一条距离
//            if (ucout == 0) act.insert();
//        } else
        act.insert();

        Wrapper<Userstat> uentity = new EntityWrapper<Userstat>().eq("uid", uid);
        Userstat ustat = userstatService.selectOne(uentity);

        Wrapper<Userstat> ventity = new EntityWrapper<Userstat>().eq("uid", vuid);
        Userstat vstat = userstatService.selectOne(ventity);

        logger.debug("=========ustat=" + JSON.toJSONString(ustat));
        logger.debug("=========vstat=" + JSON.toJSONString(vstat));

        if (ustat == null) {
            this.initUstat(vuid, vstat, user.getGuid(), mid, mpid, type);
        } else {
            this.updateUstat(ustat, vstat, type, ucout, vcout);
        }
    }

    // 被访问用户的行为数据统计
    private Userstat initUstat(Long vuid, Userstat vstat, String guid, Long mid, Long mpid, int type) {

        Userstat ustat = new Userstat();
        ustat.setUid(vuid);
        ustat.setGuid(guid);
        ustat.setMid(mid);
        ustat.setMpid(mpid);

        ustat.setAccess(type == ActgxType.access.getVal() ? 1 : 0);
        ustat.setVisit(type == ActgxType.visit.getVal() ? 1 : 0);

        ustat.setAccessc(type == ActgxType.access.getVal() ? 1 : 0);
        ustat.setVisitc(type == ActgxType.visit.getVal() ? 1 : 0);

        ustat.setGfav(type == ActgxType.gfav.getVal() ? 1 : 0);
        ustat.setUfav(type == ActgxType.ufav.getVal() ? 1 : 0);
        ustat.setZuan(type == ActgxType.dianzan.getVal() ? 1 : 0);

        ustat.setKehu(type == ActgxType.addkehu.getVal() ? 1 : 0);

        ustat.setKehu(type == ActgxType.share.getVal() ? 1 : 0);
        ustat.setShare(type == ActgxType.share.getVal() ? 1 : 0);
        ustat.setCall(type == ActgxType.call.getVal() ? 1 : 0);

        ustat.setShuo(0);
        ustat.setDongtai(0);
        ustat.setKehu(0);
        ustat.setRenqi(1);
        ustat.setState(1);
        ustat.setIsHuoyue(1);
        ustat.setLastvtime(new Date());
        ustat.setCreatetime(new Date());
        ustat.insert();

        if (type == ActgxType.visit.getVal()) {
            vstat.setAccess(vstat.getAccessc() + 1);
            vstat.setAccessc(vstat.getAccessc() + 1);
            vstat.updateById();
        }

        return ustat;
    }

    private void updateUstat(Userstat ustat, Userstat vstat, int type, int cout, int vcout) {
        logger.debug("=========updateUstat type=" + type);
        logger.debug("=========updateUstat ustat=" + JSON.toJSONString(ustat));
        cout = cout == 0 ? 1 : 0;
        ustat.setModifytime(new Date());
        vstat.setModifytime(new Date());
        vstat.setRenqi(vstat.getRenqi() + 1);// 任何操作，对方人气+1

        if (type == ActgxType.access.getVal()) {
            ustat.setAccess(ustat.getAccess() + cout);//人数
            ustat.setAccessc(ustat.getAccessc() + 1);//次数
        } else if (type == ActgxType.visit.getVal()) {
            ustat.setVisit(ustat.getVisit() + cout);//人数
            ustat.setVisitc(ustat.getVisitc() + 1);//次数

            vstat.setAccess(vstat.getAccess() + cout);
            vstat.setAccessc(vstat.getAccessc() + 1);

            userstatService.update(ustat, new EntityWrapper<Userstat>().eq("id", ustat.getId()));
            vstat.updateById();

        } else if (type == ActgxType.gfav.getVal()) {
            ustat.setGfav(ustat.getGfav() + cout);

        }else if (type == ActgxType.ufav.getVal()){
            ustat.setUfav(ustat.getUfav() + cout);

        }else if (type == ActgxType.dianzan.getVal()) {
            vstat.setZuan(ustat.getZuan() + 1);

        }else if (type == ActgxType.addkehu.getVal()) {
            ustat.setKehu(ustat.getKehu() + cout);
            userstatService.update(ustat, new EntityWrapper<Userstat>().eq("id", ustat.getId()));

        }else if (type == ActgxType.share.getVal()) {

            vstat.setShare(ustat.getShare() + 1);
        }else if (type == ActgxType.call.getVal()) {


            vstat.setCall(ustat.getCall() + 1);
        }

        vstat.updateById();
        logger.debug("=========updateUstat 111");
        logger.debug("=========updateUstat updateById ok");

//        return ustat;
    }

}
